
#include "CameraDriveImagSeq.h"
#include <math.h>


void CameraDriveImagSeq::buildName(const char* pattern,int indexCurrentImage,int numberZeros,const char* extencao, string& ret )
{	
	char nomeArquivo [1024];
	char patternString [64];
	string mIndexString, mNameCurrentImage;
	sprintf_s(patternString,63,"%%s%%0%d.f%%s",numberZeros);
	sprintf_s(nomeArquivo,patternString,pattern,(float)indexCurrentImage,extencao);
	ret = nomeArquivo;
}

CameraDriveImagSeq::CameraDriveImagSeq(  char * rootName ,int ini, int final,int zeros, char ext[10] ){
	
	strcpy(_nameRootText,rootName);
	_image = NULL;
	_imageRGB = NULL;
	_index = ini;
	_initialFrame = ini;
	_finalFrame = final;
	_numZeros = zeros;
	strcpy(_extension,ext);
}

IplImage*  CameraDriveImagSeq::getFrame( bool next ){
	
	string nameCurrentImage;

	if(next)
		_index++;
	if (_index > _finalFrame)
	{
		_index = _finalFrame;
	}

	if(_image != NULL)
	{
		cvReleaseImage( &_image );

	}
	if(_imageRGB != NULL)
	{
		cvReleaseImage( &_imageRGB );

	}
	buildName(_nameRootText,_index,_numZeros,_extension,nameCurrentImage);
	_image = cvLoadImage( (char*)nameCurrentImage.c_str() );
	if (_image)
	{
		_imageRGB = cvCloneImage(_image);
		cvConvertImage(_image,_imageRGB,CV_CVTIMG_FLIP|CV_CVTIMG_SWAP_RB);
	}
	

	return _image;
}

void CameraDriveImagSeq::setPositionIndex( int frame )
{
	_index = frame;
	if (_index > _finalFrame)
	{
		_index = _finalFrame;
	}
	if (_index < _initialFrame)
	{
		_index = _initialFrame;
	}
}



int CameraDriveImagSeq::getHeight( void )
{
	if(_image == NULL)
		return 0;
	return _image->height;
}
int CameraDriveImagSeq::getWidth( void )
{
	if(_image == NULL)
		return 0;
	return _image->width;
}

CameraDriveImagSeq::~CameraDriveImagSeq( void  )
{		
	cvReleaseImage( &_image );
}

void CameraDriveImagSeq::stepF( void )
{
	setPositionIndex(_index+1);
}

void CameraDriveImagSeq::stepR( void )
{
	setPositionIndex(_index-1);
}

void CameraDriveImagSeq::setPositionIndexbyPercent( double val )
{
	setPositionIndex((int)(_initialFrame + (val*(_finalFrame-_initialFrame))));
}

double CameraDriveImagSeq::getPositionIndexbyPercent( void )
{
	return ((double)_index-_initialFrame)/((double)_finalFrame-_initialFrame);
}

IplImage* CameraDriveImagSeq::getFrameRGB()
{
	return _imageRGB;
}